<template>
  <v-dialog
    v-model="dialogVisible"
    width="600px"
  >
    <v-card>
      <v-card-title class="text-h5 grey lighten-2">
        我的图片
      </v-card-title>
      <v-card-text>
        <div class="image-lib-btn">
          <v-file-input
            hint="只能上传jpg/png/gif文件，且不超过2M"
            placeholder="点击上传"
            persistent-hint
            prepend-icon="mdi-image"
            :rules="[v => !!v || '文件必选']"
            accept=".jpg,/png,.gif"
            show-size
            :disabled="uploadLoading"
            :loading="uploadLoading"
            required
            @change="uploadFile"
          />
        </div>
        <div v-if="imageList.length" class="image-list-wrapper">
          <div v-for="(item, index) in imageList" :key="index" class="image-item" @click="handleImageClick(item.url)">
            <img :src="item.url" alt="">
          </div>
        </div>
        <div v-else class="mt-5 pa-12 text-center grey lighten-2">暂无数据</div>
      </v-card-text>
    </v-card>
  </v-dialog>
</template>

<script>
import $bus from '@/eventBus'

export default {
  name: 'ImageLibs',
  data() {
    return {
      dialogVisible: false,
      uploading: false,
      hasLoadData: false,
      imageList: [],
      selectId: '',
      uploadLoading: false
    }
  },
  watch: {
    dialogVisible(val) {
      if (val && !this.uploading) {
        this.getMyImages()
      }
    }
  },
  created() {
    $bus.$on('show-select-image', selectId => {
      this.dialogVisible = true
      this.selectId = selectId
    })
  },
  methods: {
    uploadFile(file) {
      const params = new FormData()
      params.append('file', file)
      this.uploading = true
      // this.$API.uploadImage(params).then(res => {
      //   this.uploading = false
      //   this.imageList.splice(0, 0, res.body)
      // }).catch(() => {
      //   this.uploading = true
      // })
    },
    getMyImages() {
      this.hasLoadData = true
      // this.$API.getMyImages().then(res => {
      //   this.imageList = res.body || []
      // })
    },
    /**
			 * 点击图片
			 * @param url
			 */
    handleImageClick(url) {
      $bus.$emit('select-image', this.selectId, url)
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.image-list-wrapper{
  height: 400px;
  padding-top: 20px;
  .image-item{
    width: 120px;
    height: 120px;
    float: left;
    background: #eee 50%/contain no-repeat;
    cursor: pointer;
    justify-content:center;
    align-items:center;
    display: flex;
    transition: all 0.28s;
    margin: 5px;
    &:hover{
      box-shadow: 0 0 16px 0 rgba(0,0,0,.16);
      transform: translate3d(0,-2px,0);
    }
    img{
      display: inline-block;
      max-width: 100%;
      max-height: 100%;
    }

  }
}
</style>
